/***************************************************
 ** @Desc : This file for 用户加减款历史操作数据模型
 ** @Time : 2019.04.15 17:45 
 ** @Author : Joker
 ** @File : user_history
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.04.15 17:45
 ** @Software: GoLand
****************************************************/
package models

import (
	"github.com/astaxie/beego/orm"
	"recharge/sys"
	"recharge/utils"
)

type UserHistory struct {
	Id           int
	Version      int
	UserId       int
	UserName     string
	CreateTime   string
	EditTime     string
	Addition     float64
	Deduction    float64
	FrozenAdd    float64 //冻结,冻结加,
	FrozenDed    float64 //冻结减
	UsableAmount float64
	TotalAmount  float64
	FrozenAmount float64
}

func (*UserHistory) TableEngine() string {
	return "INNODB"
}

func (*UserHistory) TableName() string {
	return UserHistoryTBName()
}

//读取单个用户历史信息通过id
func (*UserHistory) SelectOneUserHistoryById(id int) (info UserHistory) {
	om := orm.NewOrm()
	err := om.Raw("select * from user_history where user_id = ? for update", id).QueryRow(&info)
	if err != nil {
		sys.LogError("SelectOneUserHistoryById failed to select user: ", err)
	}
	return info
}

// 修改用户历史信息
func (*UserHistory) UpdateUserHistory(history UserHistory) int {
	om := orm.NewOrm()
	_, err := om.QueryTable(UserHistoryTBName()).Filter("id", history.Id).Update(orm.Params{
		"version":       orm.ColValue(orm.ColAdd, 1),
		"edit_time":     history.EditTime,
		"addition":      history.Addition,
		"deduction":     history.Deduction,
		"frozen_add":    history.FrozenAdd,
		"frozen_ded":    history.FrozenDed,
		"usable_amount": history.UsableAmount,
		"total_amount":  history.TotalAmount,
		"frozen_amount": history.FrozenAmount,
	})
	if err != nil {
		sys.LogError("UpdateUserHistory failed to update for:", err)
		return utils.FAILED_FLAG
	}
	return utils.SUCCESS_FLAG
}

/* *
 * @Description: 添加用户历史信息
 * @Author: Joker
 * @Date: 2019-4-15 17:53:58
 * @Param: sr: 用户历史信息
 * @return: int: 判断成功的标识
 * @return: int64:	在表中哪一行插入
 **/
func (*UserHistory) InsertUserHistory(sr UserHistory) (int, int64) {
	om := orm.NewOrm()
	in, _ := om.QueryTable(UserHistoryTBName()).PrepareInsert()
	id, err := in.Insert(&sr)
	if err != nil {
		sys.LogError("InsertUserHistory failed to insert for: ", err)
		return utils.FAILED_FLAG, id
	}
	return utils.SUCCESS_FLAG, id
}
